from flask import Flask, request, jsonify, render_template, Response
import requests
import json
import json
app = Flask(__name__)
@app.route('/')
def index():
    # 使用render_template返回index.html页面
    return render_template('index.html')
headers = {
    'accept': 'application/json',
    'Content-Type': 'application/json',
}

def generate_stream(data):
    # 这里定义你的生成器逻辑，该逻辑应该向客户端发送数据块
    for line in data.iter_content(None, decode_unicode=True):
        json_data = json.loads(line.split('data: ')[-1].rstrip())
        # print(f"json_data:{json_data}")
        # yield f"data: {json.dumps(json_data)}\n\n".encode('utf-8')
        yield f"data: {json.dumps(json_data, ensure_ascii=False)}\n\n".encode('utf-8')
        # yield json.dumps(line).encode('utf-8')
        # yield line

@app.route('/send_message', methods=['POST'])
def send_message():
    data = request.get_json()
    print(f"data:{data}")
    response = requests.post('http://0.0.0.0:7861/chat/chat',json=data, stream=True, headers=headers)
    return Response(generate_stream(response), content_type='text/event-stream')

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=5001,debug=True)
    # app.run(host="192.168.6.143",port=5000,debug=True)

